import uuid
import hmac
import hashlib
import logging
from google.appengine.ext import db

class SecretKey(db.Model):
  tk_name = db.StringProperty(required=True)
  uuid = db.StringProperty(required=True)

class DuplicateKeyException(Exception):
  pass

class KeyNotFoundException(Exception):
  pass

def getAllKey():
  """Returns a Query object that represents all SecretKey entities and can be iterable"""
  
  return SecretKey.all()

def getKey(tk):
  secret_key = SecretKey.gql("WHERE tk_name = :1", tk).get()
  if not secret_key:
    logging.warning("Secret Key not found in database!")
    return None
  else:
    return secret_key.uuid
  
def createKey(tk):
  if SecretKey.gql("WHERE tk_name = :1", tk).count(1) > 0:
    raise DuplicateKeyException
  secret_key = SecretKey(tk_name=tk, uuid=uuid.uuid1().hex)
  db.put(secret_key)

def regenerateKey(uni_key):
  secret_key = SecretKey.get(uni_key)
  if not secret_key:
    raise KeyNotFoundException
  secret_key.uuid = uuid.uuid1().hex
  db.put(secret_key)
  #return secret_key.uuid

def deleteKey(uni_key):
  secret_key = SecretKey.get(uni_key)
  if not secret_key:
    raise KeyNotFoundException
  db.delete(secret_key)

def validate(tk, auth):
  logging.debug("validate(): validating secret key for tk: %s", tk)
  if hmac.new(getKey(tk), tk, hashlib.sha256).hexdigest() == auth:
    logging.debug("validate(): validation succeeded for tk: %s", tk)
    return True
  else:
    logging.debug("validate(): validation failed for tk: %s", tk)
    return False

def getHMAC(tk):
  logging.debug("getHMAC(): Attention: This function is for testing purpose only. tk: %s", tk)
  hmacValue = hmac.new(getKey(tk), tk, hashlib.sha256).hexdigest()
  logging.debug("getHMAC(): HMAC=%s", hmacValue)
  return hmacValue

